package shell

import (
	"bytes"
	"golang.org/x/text/encoding/simplifiedchinese"
	"os/exec"
	"runtime"
)

type Charset string

const (
	UTF8    = Charset("UTF-8")
	GB18030 = Charset("GB18030")
)

func Shell(command string) (string, error) {
	var stdout bytes.Buffer
	var err error

	if runtime.GOOS == "windows" {
		cmd := exec.Command("cmd", "/c", command)
		cmd.Stdout = &stdout
		cmd.Stderr = &stdout
		err = cmd.Run()
		return ConvertByte2String(stdout.Bytes(), GB18030), err
	} else {
		cmd := exec.Command("bash", "-c", command)
		cmd.Stdout = &stdout
		cmd.Stderr = &stdout
		err = cmd.Run()
		return stdout.String(), err
	}
}

func ConvertByte2String(byte []byte, charset Charset) string {
	var str string
	switch charset {
	case GB18030:
		decodeBytes, _ := simplifiedchinese.GB18030.NewDecoder().Bytes(byte)
		str = string(decodeBytes)
	case UTF8:
		fallthrough
	default:
		str = string(byte)
	}
	return str
}
